package com.wswy.wzcx.ui.other;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by wangduheng26 on 2018/1/19.
 * wangduheng26@gmail.com
 */

public class PhoneTextWatcher implements TextWatcher {
    private static final char SEPARATOR = ' ';

    private EditText editText;

    public PhoneTextWatcher(EditText editText) {
        this.editText = editText;
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (s == null || s.length() == 0) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == SEPARATOR) {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != SEPARATOR) {
                    sb.insert(sb.length() - 1, SEPARATOR);
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == SEPARATOR) {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            editText.setText(sb.toString());
            editText.setSelection(index);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    public static String getRealPhoneNumber(EditText editText) {
        Editable text = editText.getText();
        if (TextUtils.isEmpty(text)) {
            return null;
        }

        return text.toString().replaceAll(String.valueOf(SEPARATOR), "");

    }
}
